package com.eastcom.groovy.tools.file;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.PBEParameterSpec

//import jxl.Workbook;
//import jxl.read.biff.BiffException;
//import jxl.write.WritableSheet;
//import jxl.write.WritableWorkbook;
//import jxl.write.WriteException;

/**
 * 辅助测试的文件工具类
 * @author 左潇龙
 * @version 1.0.0
 * @since 1.0.0
 */
public class FileUtils extends org.apache.commons.io.FileUtils{

	public FileUtils(){}

	public static String read(String fileName) throws IOException{
		File file = new File(fileName);
		FileInputStream fileInputStream = new FileInputStream(file);
		byte[] bytes = new byte[(int) file.length()];
		fileInputStream.read(bytes);
		return new String(bytes);
	}

	public static void write(String fileName,String xml) throws IOException{
		OutputStream outputStream = new FileOutputStream(new File(fileName));
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xml.getBytes());
		int len = -1;
		byte[] bytes = new byte[1024];
		while ((len = byteArrayInputStream.read(bytes)) != -1) {
			outputStream.write(bytes, 0, len);
		}
		outputStream.flush();
		outputStream.close();
		byteArrayInputStream.close();
	}
	/**

	 * 使用文件通道的方式复制文件

	 * 

	 * @param s

	 *            源文件

	 * @param t

	 *            复制到的新文件

	 */

	public void fileChannelCopy(File s, File t) {

		FileInputStream fi = null;

		FileOutputStream fo = null;

		FileChannel ins = null;

		FileChannel out = null;

		try {

			fi = new FileInputStream(s);

			fo = new FileOutputStream(t);

			ins = fi.getChannel();//得到对应的文件通道

			out = fo.getChannel();//得到对应的文件通道

			ins.transferTo(0, ins.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				fi.close();

				ins.close();

				fo.close();

				out.close();

			} catch (IOException e) {

				e.printStackTrace();

			}

		}

	}

	public static void copyFile(File sourceFile, File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}

	// 复制文件夹
	public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
		// 新建目标目录
		(new File(targetDir)).mkdirs();
		// 获取源文件夹当前下的文件或目录
		File[] file = (new File(sourceDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				// 源文件
				File sourceFile = file[i];
				// 目标文件
				File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
				copyFile(sourceFile, targetFile);
			}
			if (file[i].isDirectory()) {
				// 准备复制的源文件夹
				String dir1 = sourceDir + "/" + file[i].getName();
				// 准备复制的目标文件夹
				String dir2 = targetDir + "/" + file[i].getName();
				copyDirectiory(dir1, dir2);
			}
		}
	}

	/**
	 * 
	 * @param srcFileName
	 * @param destFileName
	 * @param srcCoding
	 * @param destCoding
	 * @throws java.io.IOException
	 */
	public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding) throws IOException {// 把文件转换为GBK文件
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
			char[] cbuf = new char[1024 * 5];
			int len = cbuf.length;
			int off = 0;
			int ret = 0;
			while ((ret = br.read(cbuf, off, len)) > 0) {
				off += ret;
				len -= ret;
			}
			bw.write(cbuf, 0, off);
			bw.flush();
		} finally {
			if (br != null)
				br.close();
			if (bw != null)
				bw.close();
		}
	}

	/**
	 *
	 * @param filepath
	 * @throws java.io.IOException
	 */
	public static void del(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File[] delFile = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						del(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					delFile[j].delete();// 删除文件
				}
			}
		}
	}
	/**
	 * 设置缓冲值
	 */
	static final int BUFFER = 8192;
	
	private static final String ALGORITHM = "PBEWithMD5AndDES";

	public static void zip(String zipFileName, String inputFile,String pwd) throws Exception {
		zip(zipFileName, new File(inputFile), pwd);
	}
	/**
	 * 功能描述：压缩指定路径下的所有文件
	 * @param zipFileName 压缩文件名(带有路径)
	 * @param inputFile   指定压缩文件夹
	 * @return
	 * @throws Exception
	 */
	public static void zip(String zipFileName, String inputFile) throws Exception {
		zip(zipFileName, new File(inputFile), null);
	}

	
	/**
	 * 功能描述：压缩文件对象
	 * @param zipFileName 压缩文件名(带有路径)
	 * @param inputFile   文件对象
	 * @return
	 * @throws Exception
	 */
	public static void zip(String zipFileName, File inputFile,String pwd) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
		zip(out, inputFile, "",pwd);
		out.close();
	}

	/**
	 *
	 * @param out  压缩输出流对象
	 * @param file
	 * @param base
	 * @throws Exception
	 */
	public static void zip(ZipOutputStream outputStream, File file, String base,String pwd) throws Exception {
		if (file.isDirectory()) {
			File[] fl = file.listFiles();
			outputStream.putNextEntry(new ZipEntry(base + "/"));
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(outputStream, fl[i], base + fl[i].getName(), pwd);
			}
		}
		else {
			outputStream.putNextEntry(new ZipEntry(base));
			FileInputStream inputStream = new FileInputStream(file);
			//普通压缩文件
			if(pwd == null || pwd.trim().equals("")){
				int b;
				while ((b = inputStream.read()) != -1){
					outputStream.write(b);
				}
				inputStream.close();
			}
			//给压缩文件加密
			else{
				PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
				SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
				SecretKey passwordKey = keyFactory.generateSecret(keySpec);
				byte[] salt = new byte[8];
				Random rnd = new Random();
				rnd.nextBytes(salt);
				int iterations = 100;
				PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
				Cipher cipher = Cipher.getInstance(ALGORITHM);
				cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);
				outputStream.write(salt);
				byte[] input = new byte[64];
				int bytesRead;
				while ((bytesRead = inputStream.read(input)) != -1) {
					byte[] output = cipher.update(input, 0, bytesRead);
					if (output != null){
						outputStream.write(output);
					}
				}
				byte[] output = cipher.doFinal();
				if (output != null){
					outputStream.write(output);
				}
				inputStream.close();
				outputStream.flush();
				outputStream.close();
			}
		}
		file.delete();
	}

	public static void unzip(String zipFileName, String outputDirectory)throws Exception {
		ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFileName));
		unzip(inputStream, outputDirectory, null);
	}
	
	
	/**
	 * 功能描述：将压缩文件解压到指定的文件目录下
	 * @param zipFileName      压缩文件名称(带路径)
	 * @param outputDirectory  指定解压目录
	 * @return
	 * @throws Exception
	 */
	public static void unzip(String zipFileName, String outputDirectory, String pwd)throws Exception {
		ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFileName));
		unzip(inputStream, outputDirectory, pwd);
	}
	
	
	public static void unzip(File zipFile, String outputDirectory, String pwd)throws Exception {
		ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFile));
		unzip(inputStream, outputDirectory,pwd);
	}
	
	
	public static void unzip(ZipInputStream inputStream, String outputDirectory, String pwd) throws Exception{
		ZipEntry zipEntry = null;
		FileOutputStream outputStream = null;
		try{
			while ((zipEntry = inputStream.getNextEntry()) != null) {
				if (zipEntry.isDirectory()) {
					String name = zipEntry.getName();
					name = name.substring(0, name.length() - 1);
					File file = new File(outputDirectory + File.separator + name);
					file.mkdir();
				}
				else {
					File file = new File(outputDirectory + File.separator + zipEntry.getName());
					file.createNewFile();
					outputStream = new FileOutputStream(file);
					//普通解压缩文件
					if(pwd == null || pwd.trim().equals("")){
						int b;
						while ((b = inputStream.read()) != -1){
							outputStream.write(b);
						}
						outputStream.close();
					}
					//解压缩加密文件
					else{
						PBEKeySpec keySpec = new PBEKeySpec(pwd.toCharArray());
						SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
						SecretKey passwordKey = keyFactory.generateSecret(keySpec);
						byte[] salt = new byte[8];
						inputStream.read(salt);
						int iterations = 100;
						PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);
						Cipher cipher = Cipher.getInstance(ALGORITHM);
						cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);
						byte[] input = new byte[64];
						int bytesRead;
						while ((bytesRead = inputStream.read(input)) != -1) {
							byte[] output = cipher.update(input, 0, bytesRead);
							if (output != null){
								outputStream.write(output);
							}
						}
						byte[] output = cipher.doFinal();
						if (output != null){
							outputStream.write(output);
						}
						outputStream.flush();
						outputStream.close();
					}
				}
			}
			inputStream.close();
		}
		catch(IOException ex){
			throw new Exception("解压读取文件失败");
		}
		catch(Exception ex){
			throw new Exception("解压文件密码不正确");
		}
		finally{
			inputStream.close();
			outputStream.flush();
			outputStream.close();
		}
	}
	
	
	public static void main(String[] args) {
		try {
			zip("E:\\test。zip", "E:\\test");
			System.out.println("success");
		}
		catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
}
